package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.Service.DormitoryService;
import org.gdpu.Service.StudentService;
import org.gdpu.Service.UserService;
import org.gdpu.base.PageView;
import org.gdpu.model.Dormitory;
import org.gdpu.model.DormitoryState;
import org.gdpu.model.Mailbox;
import org.gdpu.model.Student;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.ExcelUtil;
import org.gdpu.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-3-4
 * Time: 上午8:59
 * To change this template use File | Settings | File Templates.
 */
@Component("student")
@Scope("prototype")
public class StudentAction extends MyActionSupport implements ModelDriven<StudentVO> {

    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;
    private final StudentVO studentVO = new StudentVO();
    private final static Logger logger = LogManager.getLogger(StudentAction.class);
    private StudentService studentService;
    private DormitoryService dormitoryService;
    private static String SAVE_PATH_DIR = "D:/Dormitory/_file/_excel/_student/";

    public String findStuByDormitoryId() {
        if (studentVO.getDormitoryId().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请输入宿舍编号！');location.href='/page/searchManagement/findDormitoryById.jsp';</script>");
            return ERROR;
        } else if (studentVO.getDormitoryId().length() != 4) {
            studentVO.setResultMessage("<script>alert('请输入4位宿舍编号！');location.href='/page/searchManagement/findDormitoryById.jsp';</script>");
            return ERROR;
        }

        List<Student> sts = studentService.findStudent("dormitory+campus", studentVO.getDormitoryId() + studentVO.getCampus());
        if (sts.isEmpty()) {
            studentVO.setResultMessage("<script>alert('宿舍编号不存在！');location.href='/page/searchManagement/findDormitoryById.jsp';</script>");
            return ERROR;
        }
        studentVO.getStudents().addAll(sts);
        logger.info("find student by dormitoryId:" + studentVO.getDormitoryId());
        view = "/page/searchManagement/findDormitoryById.jsp";
        return VIEW;
    }

    public String findStuByStuId() {
        if (Integer.valueOf(studentVO.getStuId()) == 0) {
            studentVO.setResultMessage("<script>alert('请输入学生学号！');location.href='/page/searchManagement/findDormitoryByStu.jsp';</script>");
            return ERROR;
        }
        Student student = studentService.findStudent("studentId", studentVO.getStuId()).get(0);
        if (student == null) {
            studentVO.setResultMessage("<script>alert('学生学号不存在！');location.href='/page/searchManagement/findDormitoryByStu.jsp';</script>");
            return ERROR;
        }
        studentVO.getStudents().add(student);
        logger.info("find student by studentId:" + studentVO.getStuId());
        view = "/page/searchManagement/findDormitoryByStu.jsp";
        return VIEW;
    }

    public String findStuByStuName() {
        if (studentVO.getStuName().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请输入学生姓名！');location.href='/page/searchManagement/findDormitoryByStu.jsp';</script>");
            return ERROR;
        }
        List<Student> sts = studentService.findStudent("studentName", studentVO.getStuName());
        if (sts.isEmpty()) {
            studentVO.setResultMessage("<script>alert('学生姓名不存在！');location.href='/page/searchManagement/findDormitoryByStu.jsp';</script>");
            return ERROR;
        }
        studentVO.getStudents().addAll(sts);
        logger.info("find student by studentName:" + studentVO.getStuName());
        view = "/page/searchManagement/findDormitoryByStu.jsp";
        return VIEW;
    }

    public String findStudentByBuilding(){
        if (studentVO.getCampus().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请选择校区！');location.href='/page/searchManagement/findDormitoryByBuilding.jsp';</script>");
            return ERROR;
        }

        if (studentVO.getBuilding().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请选择宿舍楼！');location.href='/page/searchManagement/findDormitoryByBuilding.jsp';</script>");
            return ERROR;
        }
        List<Student> sts = studentService.findStudent("building", studentVO.getBuilding() + studentVO.getCampus());
        if(sts.isEmpty()){
            studentVO.setResultMessage("<script>alert('没有数据，请重新选择！');location.href='/page/searchManagement/findDormitoryByBuilding.jsp';</script>");
            return ERROR;
        }
        String fileName = ChangeTime.formatDate(ChangeTime.getCurrentDate()) + ".xlsx";
        excelUtil.exportExcelByPath(SAVE_PATH_DIR + fileName, sts, Student.class, true, studentVO.getBuilding() + "栋 学生宿舍信息（"+studentVO.getCampus()+"）");
        System.out.println(SAVE_PATH_DIR + fileName);
        //TODO:在线浏览EXCEL表格，白云，文件地址为SAVE_PATH_DIR + fileName
        //studentVO.setStudents(sts);
        logger.trace("search students records success");
        view = "/page/searchManagement/findDormitoryByBuilding.jsp";
        return VIEW;
    }

    public String findStudentByCollegeAndMajor() {

        List<Student> sts = new ArrayList<Student>();

        if (studentVO.getCampus().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请选择校区！');location.href='/page/searchManagement/findDormitoryByCampus.jsp';</script>");
            return ERROR;
        }

        else if (studentVO.getCollege().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请选择学院！');location.href='/page/searchManagement/findDormitoryByCampus.jsp';</script>");
            return ERROR;
        }

        else if (studentVO.getMajor().isEmpty())
            sts = studentService.findStudent("college", studentVO.getCollege());
        else
            sts = studentService.findStudent("major", studentVO.getMajor());
        if(sts.isEmpty()){
            studentVO.setResultMessage("<script>alert('没有数据，请重新选择！');location.href='/page/searchManagement/findDormitoryByCampus.jsp';</script>");
            return ERROR;
        }

        String fileName = ChangeTime.formatDate(ChangeTime.getCurrentDate()) + ".xlsx";
        if(studentVO.getMajor().isEmpty())
            excelUtil.exportExcelByPath(SAVE_PATH_DIR + fileName, sts, Student.class, true, sts.get(0).getMajor().getCollege().getCollegeName()+ " 学生宿舍信息（"+studentVO.getCampus()+"）");
        else
            excelUtil.exportExcelByPath(SAVE_PATH_DIR + fileName, sts, Student.class, true, sts.get(0).getMajor().getMajorName() + " 学生宿舍信息（"+studentVO.getCampus()+"）");
        System.out.println(SAVE_PATH_DIR + fileName);
        //TODO:在线浏览EXCEL表格，白云，文件地址为SAVE_PATH_DIR + fileName




        logger.trace(" search students records success");
       // studentVO.setStudents(sts);
        view = "/page/searchManagement/findDormitoryByCampus.jsp";
        return VIEW;
    }

    public String setDormitory(){
        if (studentVO.getDormitory().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请选择分配宿舍！');location.href='Student!findNoDormitory.action';</script>");
            return ERROR;
        }
        studentService.setDormitory(studentVO.getStuIds(),studentVO.getDormitory());
        studentVO.setResultMessage("<script>alert('操作成功！');location.href='Student!findNoDormitory.action';</script>");
        return SUCCESS;
    }

    public String findNoDormitory() {
        /** 每页显示的结果数 **/
        int maxResult = 12;
        /** 封装的页面数据 **/
        PageView<Student> pageView = new PageView<Student>(maxResult,
                studentVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引

        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("studentId", "asc");
        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        jpql.append(" and o.dormitory IS NULL");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();

        pageView.setQueryResult(studentService.getScrollData(Student.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));
        studentVO.setPageView(pageView);
        if(pageView.getRecords().isEmpty()){
            studentVO.setResultMessage("<script>alert('所有学生均已分配宿舍！');location.href='/page/dormitoryManagement/dormitoryIndex.jsp';</script>");
            return ERROR;
        }
        studentVO.setCampus(pageView.getRecords().get(0).getMajor().getCollege().getCampus().getCampusName());
        view = "/page/dormitoryManagement/findNoDormitoryStu.jsp";
        return VIEW;
    }

    public String checkIn() {
        String[] stuIds = studentVO.getStuId().split(",");
        StringBuffer dor = new StringBuffer();
        for (String no : stuIds) {
            Student student = studentService.findStudent("studentId", Integer.valueOf(no)).get(0);
            String temp = studentService.checkIn(student);
            if (temp.isEmpty()) {
                dor.append("<div style='color:RED'>学生：").append(student.getStudentName()).append("(").append(student.getStudentId()).append("),未能安排到合适的宿舍！").append("\n</div>");
            } else
                dor.append("学生：").append(student.getStudentName()).append("(").append(student.getStudentId()).append("),被安排到宿舍：").append(temp).append("\n");
        }
        studentVO.setResultMessage(dor.toString());
        return SUCCESS;
    }

    public String checkOut() {
        return SUCCESS;
    }

    public String importStudent(){
        try {
            if (studentVO.getFileName().isEmpty()) {
                studentVO.setResultMessage("<script>alert('请选择文件！');location.href='" +
                        "/page/dormitoryManagement/importStudent.jsp';</script>");
                return ERROR;
            }
            List<Student> sts = new ArrayList<Student>();
            List<Object> obj = excelUtil.readExcelByPath(studentVO.getFileName(),Student.class, 1, 0);
            for (int i = 0; i < obj.size(); i++) {
                sts.add((Student) obj.get(i));
            }
            int count = 0;
            int failCount = 0;
            int empty = 0;
            StringBuffer sbr = new StringBuffer();
            for (Student student : sts) {
                if(!studentService.findStudent("studentId", student.getStudentId()).isEmpty()){
                    if(sbr.toString().equals(""))
                        sbr.append("<div style='color:RED'></br>失败记录，已存在的学生编号：</br>");
                    sbr.append(student.getStudentId()+"   ");
                    ++failCount;
                    if(failCount%8 == 0)
                        sbr.append("</br>");
                }
                else{
                    studentService.save(student);
                    if(studentService.checkIn(student).isEmpty())
                        ++empty;
                    ++count;
                }
            }
            if(empty == 0){
                studentVO.setResultMessage("成功安排新生入住，"+"共有"+obj.size()+"条记录，" +
                        "成功导入"+count+"条记录，"+"请查看数据库。</br>" +sbr);
                logger.trace("arrange the student records success");
                return SUCCESS;
            }
            else{
                return findNoDormitory();
            }
        } catch (RuntimeException e) {
            studentVO.setResultMessage(e.getMessage());
            logger.error(e);
            return ERROR;
        }
    }

    public String relocateStudent(){
        if (studentVO.getCampus().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请选择校区！');location.href='" +
                    "/page/dormitoryManagement/relocateStudent.jsp';</script>");
            return ERROR;
        }
        if (Calendar.getInstance().get(Calendar.MONTH) + 1 <= 6) {
            studentVO.setResultMessage("<script>alert('未到毕业生搬迁的时间，请到7月份再操作！');" +
                    "location.href='/page/dormitoryManagement/relocateStudent.jsp';</script>");
            return ERROR;
        }
        List<Student> sts = studentService.findStudent("relocate",studentVO.getCampus());
        if(sts.isEmpty()){
            studentVO.setResultMessage("<script>alert('没有数据，请重新选择！');location.href='/page/dormitoryManagement/relocateStudent.jsp';</script>");
            return ERROR;
        }
        // 得到下载文件目录的真实路径
        File dir = new File(SAVE_PATH_DIR);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String date = ChangeTime.formatDate(ChangeTime.getCurrentDate());
        excelUtil.exportExcelByPath(SAVE_PATH_DIR + date + ".xlsx", sts, Student.class,
                true, Calendar.getInstance().get(Calendar.YEAR) + "应届毕业生搬迁信息 （"+studentVO.getCampus()+"）");
        //文件路径是SAVE_PATH_DIR + date + ".xlsx"
        for(Student student : sts){
            Dormitory dormitory = dormitoryService.find(Dormitory.class,student.getDormitory().getId());
            dormitory.setNum(dormitory.getNum() - 1);
            if(dormitory.getNum() == 0)
                dormitory.setDormitoryState(DormitoryState.EMPTY);
            else
                dormitory.setDormitoryState(DormitoryState.NOT_FULL);
            studentService.delete(Student.class,student.getStudentId());
        }
        studentVO.setResultMessage("成功导出毕业生信息，"+"共有"+sts.size()+"条记录，" +
                "成功导出"+sts.size()+"条记录，"+"请查看Excel文件。</br>");
        logger.trace(" relocate students records success,file name is " + date);
        return SUCCESS;
    }

    public String findStudent(){
        if (studentVO.getIdentity().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请输入身份证号！');location.href='" +
                    "/page/file/findStudent.jsp';</script>");
            return ERROR;
        }
        if (studentVO.getStuName().isEmpty()) {
            studentVO.setResultMessage("<script>alert('请输入身份证号！');location.href='" +
                    "/page/file/findStudent.jsp';</script>");
            return ERROR;
        }
        try{
            List<Student> sts = excelUtil.readExcelByString(SAVE_PATH_DIR + "search.xls", studentVO.getIdentity().toUpperCase(), studentVO.getStuName());
            studentVO.setStudents(sts);
            view = "/page/file/findStudent.jsp";
            return VIEW;
        }catch (RuntimeException e) {
            studentVO.setResultMessage(e.getMessage());
            logger.error(e);
            return ERROR;
        }
    }

    @Resource(name = "dormitoryServiceImpl")
    public void setDormitoryService(DormitoryService dormitoryService) {
        this.dormitoryService = dormitoryService;
    }

    @Resource(name = "studentServiceImpl")
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @Override
    public StudentVO getModel() {
        return studentVO;
    }
}